import { _decorator, Button, Component, director, game, Node, sp, Sprite, tween, Vec3 } from 'cc';
import { audios } from './audios';
import { gameState } from './gameState';
import { editClick } from './editClick';
import { layerRootAction } from './layerRootAction';
import { eventDispatcher } from './eventDispatcher';
const { ccclass, property } = _decorator;

@ccclass('mainClick')
export class mainClick extends audios {
    @property(Node) edit_root: Node = null;
    @property(Button) btn_redo: Button = null;
    @property(Button) btn_remove: Button = null;
    @property(Button) btn_random: Button = null;
    @property(Node) sleeps_node:Node = null;
    start() {
        this.init_bg_sound();
        if (gameState.game_model === 0) {
            //game model
            this.edit_root.active = false;
            gameState.cur_lvl = 1;
            this.start_game();
            eventDispatcher.get_target().on(eventDispatcher.REPLAY_GAME, this.replay, this);
            eventDispatcher.get_target().on(eventDispatcher.REFRESH_BUTTONS, this.refresh_buttons, this);
        } else {
            //edit model
            this.edit_root.active = true;
            this.edit_root.getChildByName("edit").getComponent(editClick).start_edit();
        }
    }
    update(deltaTime: number) {}
    start_game() {
        this.sleeps_tween(()=>{
        gameState.reset_ad_times();
        let layer_root = this.node.getChildByName("layer_root").getComponent(layerRootAction);
        layer_root.start_game();
        this.refresh_buttons();
        });
    }
    private sleeps_tween(callback:Function){
        this.sleeps_node.active = true;
        this.sleeps_node.setPosition(350,0);

        tween(this.sleeps_node)
        .to(0.8,{position:new Vec3(-350,0)})
        .call(()=>{
            callback();
        })
        .to(0.5,{position:new Vec3(-900,0)})
        .call(()=>{
            this.sleeps_node.active = false;
        })
        .start();
    }
    next_level() {
        gameState.cur_lvl++;
        if(gameState.cur_lvl>gameState.get_max_lvl())gameState.cur_lvl = 1;
        this.start_game();
    }
    replay() {
        gameState.cur_lvl = 1;
        this.start_game();
    }
    backClick() {
        this.stop_bg_sound()
        director.loadScene("home");
    }
    refresh_buttons(){
        if(gameState.ad_redo_times<=0){
            this.btn_redo.getComponent(Sprite).grayscale = true;
        }else{
            this.btn_redo.getComponent(Sprite).grayscale = false; 
        }
        if(gameState.ad_remove_times<=0){
            this.btn_remove.getComponent(Sprite).grayscale = true;
        }else{
            this.btn_remove.getComponent(Sprite).grayscale = false; 
        }
        if(gameState.ad_random_times<=0){
            this.btn_random.getComponent(Sprite).grayscale = true;
        }else{
            this.btn_random.getComponent(Sprite).grayscale = false; 
        }
    }
    
}


